﻿using Microsoft.Extensions.Options;
using ShiTong.Forum.Repositories;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;



namespace FocusCareer.Repositories
{
    public class QueryDbConnection : IDisposable
    {
        private IDbConnection _dbConnection;
        private IOptions<DbSettings> _dbSettings;

        public Guid ConnectionId { get; private set; }
        public QueryDbConnection(IOptions<DbSettings> dbSettings)
        {
            ConnectionId = Guid.NewGuid();
            _dbSettings = dbSettings;
        }

        public IDbConnection DbConnection {
            get {
                if (_dbConnection==null)
                {
                    _dbConnection = new SqlConnection(_dbSettings.Value.ConnectionString);
                }
                if (_dbConnection.State== ConnectionState.Closed) {
                    _dbConnection.Open();
                }
                return _dbConnection;
            }
        }
        public void Dispose()
        {
            if (_dbConnection != null && _dbConnection.State == ConnectionState.Open)
            {
                _dbConnection.Close();
                _dbConnection.Dispose();
            }
        }
    }
}
